package gaoji;

import java.awt.Container;

//测试：生产消费者模型--》利用缓冲区解决
public class test {
	public static void main(String[] args) {
		SynContainer container = new SynContainer();

		new Productor(container).start();
		new Consumer(container).start();
	}
}

class Productor extends Thread {
	SynContainer container;

	public Productor(SynContainer container) {
		this.container = container;
	}

	@Override
	public void run() {
		for (int i = 0; i < 10; i++) {
			container.push(new Chicken(i));
			System.out.println("生产了" + i + "只鸡");
		}
	}

}

class Consumer extends Thread {
	SynContainer container;

	public Consumer(SynContainer container) {
		this.container = container;
	}

	@Override
	public void run() {

		for (int i = 0; i < 10; i++) {
			System.out.println("消费了" + container.pop() + "只鸡");
		}
	}
}

class Chicken {
	int id;

	public Chicken(int id) {
		super();
		this.id = id;
	}
}

class SynContainer {

	// 容器大小
	Chicken[] chickens = new Chicken[10];
	int count = 0;

	// 生产者放入产品
	public synchronized void push(Chicken chicken) {
		if (count == chickens.length) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 如果没有满
		chickens[count] = chicken;
		count++;

		this.notifyAll();
	}

	public synchronized Chicken pop() {
		if (count == 0) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		count--;
		Chicken chicken = chickens[count];
		this.notifyAll();
		return chicken;

	}

}